package org.example.weboj.controller;

import org.example.weboj.dto.*;
import org.example.weboj.entity.Problems;
import org.example.weboj.entity.User;
import org.example.weboj.service.IProblemsService;
import org.example.weboj.service.IUserService;
import org.example.weboj.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.util.List;
import java.util.Optional;

/**
 * 管理员控制器
 * 提供题库管理功能
 */
@RestController
@RequestMapping("/admin")
@PreAuthorize("hasRole('ADMIN')")
public class AdminController {

    @Autowired
    private IProblemsService problemsService;

    @Autowired
    private IUserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 创建新题目
     */
    @PostMapping("/problems")
    public ResponseEntity<AdminResponse<ProblemDTO>> createProblem(
            @Valid @RequestBody ProblemCreateRequest request,
            HttpServletRequest httpRequest) {
        
        try {
            // 获取当前管理员用户ID
            Long authorId = getCurrentUserId(httpRequest);
            if (authorId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(AdminResponse.error("无法获取用户信息"));
            }

            // 创建题目
            ProblemDTO problemDTO = problemsService.createProblem(request, authorId);
            
            return ResponseEntity.ok(AdminResponse.success("题目创建成功", problemDTO));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(AdminResponse.error("创建题目失败: " + e.getMessage()));
        }
    }

    /**
     * 更新题目
     */
    @PutMapping("/problems/{id}")
    public ResponseEntity<AdminResponse<ProblemDTO>> updateProblem(
            @PathVariable Long id,
            @Valid @RequestBody ProblemUpdateRequest request,
            HttpServletRequest httpRequest) {
        
        try {
            // 验证管理员权限
            if (!isAdmin(httpRequest)) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(AdminResponse.error("权限不足"));
            }

            request.setId(id);
            ProblemDTO problemDTO = problemsService.updateProblem(request);
            
            if (problemDTO == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(AdminResponse.error("题目不存在"));
            }
            
            return ResponseEntity.ok(AdminResponse.success("题目更新成功", problemDTO));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(AdminResponse.error("更新题目失败: " + e.getMessage()));
        }
    }

    /**
     * 删除题目
     */
    @DeleteMapping("/problems/{id}")
    public ResponseEntity<AdminResponse<Void>> deleteProblem(
            @PathVariable Long id,
            HttpServletRequest httpRequest) {
        
        try {
            // 验证管理员权限
            if (!isAdmin(httpRequest)) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(AdminResponse.error("权限不足"));
            }

            boolean deleted = problemsService.deleteProblem(id);
            
            if (!deleted) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(AdminResponse.error("题目不存在"));
            }
            
            return ResponseEntity.ok(AdminResponse.success("题目删除成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(AdminResponse.error("删除题目失败: " + e.getMessage()));
        }
    }

    /**
     * 批量上传题目
     */
    @PostMapping("/problems/batch")
    public ResponseEntity<AdminResponse<List<ProblemDTO>>> batchCreateProblems(
            @Valid @RequestBody List<ProblemCreateRequest> requests,
            HttpServletRequest httpRequest) {
        
        try {
            // 获取当前管理员用户ID
            Long authorId = getCurrentUserId(httpRequest);
            if (authorId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(AdminResponse.error("无法获取用户信息"));
            }

            List<ProblemDTO> problemDTOs = problemsService.batchCreateProblems(requests, authorId);
            
            return ResponseEntity.ok(AdminResponse.success(
                "批量创建成功，共创建 " + problemDTOs.size() + " 道题目", problemDTOs));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(AdminResponse.error("批量创建题目失败: " + e.getMessage()));
        }
    }

    /**
     * 获取所有题目（管理员视图，包含更多信息）
     */
    @GetMapping("/problems")
    public ResponseEntity<AdminResponse<List<ProblemDTO>>> getAllProblemsForAdmin() {
        try {
            List<ProblemDTO> problems = problemsService.getAllProblemDTOs();
            return ResponseEntity.ok(AdminResponse.success("获取题目列表成功", problems));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(AdminResponse.error("获取题目列表失败: " + e.getMessage()));
        }
    }

    /**
     * 获取题目详情（管理员视图）
     */
    @GetMapping("/problems/{id}")
    public ResponseEntity<AdminResponse<ProblemDTO>> getProblemForAdmin(@PathVariable Long id) {
        try {
            ProblemDTO problem = problemsService.getProblemDTOById(id);
            if (problem == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(AdminResponse.error("题目不存在"));
            }
            return ResponseEntity.ok(AdminResponse.success("获取题目详情成功", problem));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(AdminResponse.error("获取题目详情失败: " + e.getMessage()));
        }
    }

    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        try {
            String token = extractTokenFromRequest(request);
            if (token != null) {
                String username = jwtUtils.getUsernameFromToken(token);
                Optional<User> userOpt = userService.findByUsername(username);
                return userOpt.map(User::getId).orElse(null);
            }
        } catch (Exception e) {
            // 日志记录异常
        }
        return null;
    }

    /**
     * 验证是否为管理员
     */
    private boolean isAdmin(HttpServletRequest request) {
        try {
            String token = extractTokenFromRequest(request);
            if (token != null) {
                String username = jwtUtils.getUsernameFromToken(token);
                Optional<User> userOpt = userService.findByUsername(username);
                return userOpt.map(user -> "admin".equals(user.getRole())).orElse(false);
            }
        } catch (Exception e) {
            // 日志记录异常
        }
        return false;
    }

    /**
     * 从请求中提取JWT token
     */
    private String extractTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
} 